<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .w {
            width: 1200px;
            margin: 10px auto;
        }

        .slider-bar {
            position: absolute;
            left: 50%;
            top: 300px;
            margin-left: 600px;
            width: 45px;
            height: 200px;
            background-color: aquamarine;
        }

        .header {
            height: 150px;
            background-color: bisque;
        }

        .banner {
            height: 300px;
            background-color: bisque;
        }

        span {
            display: none;
            position: absolute;
            bottom: 0;
        }



        .main {
            height: 1000px;
            background-color: yellowgreen;
        }
    </style>
</head>

<body>
    <!-- 
        1、原先侧边栏是绝对定位
        2、当页面滚动到一定位置，侧边栏改为固定定位
        3、页面继续滚动，会让返回顶部显示出来
     -->
    <div class="slider-bar w">
        <span class="goBack">
            返回顶部
        </span>
    </div>
    <div class="header w">
        头部区域
    </div>

    <div class="banner w">
        banner区域
    </div>

    <div class="main w">
        主体部分
    </div>
    <script>
        var sliderbar = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');
        // console.log(banner.offsetTop); 获取被卷去头部的大小
        var bannerTop = banner.offsetTop;
        var sliderbarTop = sliderbar.offsetTop - bannerTop;
        var goBack = document.querySelector('.goBack');
        var main = document.querySelector('.main');
        var mainTop = main.offsetTop;
        document.addEventListener('scroll', function () {
            // console.log(11);
            // window.pageYOffset页面被卷去的头部
            //console.log(window.pageYOffset);
            // 3.当我们页面被卷去的头部大于等于了172 侧边栏就改为固定
            if (window.pageYOffset >= bannerTop) {
                sliderbar.style.position = 'fixed';
                sliderbar.style.top = sliderbarTop + 'px';
            } else {
                sliderbar.style.position = 'absolute';
                sliderbar.style.top = 300 + 'px';
            }

            if (window.pageYOffset >= mainTop) {
                goBack.style.display = 'block';
            } else {
                goBack.style.display = 'none';
            }
        })

        // 当我们点击了返回顶部模块，就让窗口滚动到页面的最上方
        goBack.addEventListener('click', function () {
            window.scroll(0, 0);
        })
    </script>
</body>

</html>